package middleware

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"project/study-go/http/base/session"
)

//SessionAuth session认证中间件
func SessionAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		session, err := session.GetSession(c.Request, "SESSIONID")
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code": 401,
				"msg":  "StatusUnauthorized",
			})
			c.Abort()
			return
		}

		_, ok := session.Values["uid"]
		if !ok {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code": 401,
				"msg":  "StatusUnauthorized",
			})
			c.Abort()
			return
		}

		c.Set("SESSIONID", session)
		c.Next()
	}
}
